package mysql

import (
	"common/models"
)

func (m Mysql) VideoCheckByUid(uid string) (b bool, ID int, err error) {
	var (
		count int64
		video *models.VideoInfo
	)
	b = false
	err = m.Db.Table("video_info").Where("video_id = ?", uid).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		b = true
		m.Db.Table("video_info").Where("video_id = ?", uid).First(&video)
		ID = int(video.ID)
		return
	}
	return
}
func (m Mysql) VideoInfoAdd(video *models.VideoInfo) (err error) {
	return m.Db.Table("video_info").Create(&video).Error
}

func (m Mysql) VideoInfoQueryByUid(uid string) (res *models.VideoInfo, err error) {
	err = m.Db.Table("video_info").Where("video_id = ?", uid).First(&res).Error
	return
}
func (m Mysql) VideoInfoQueryById(id string) (res *models.VideoInfo, err error) {
	err = m.Db.Table("video_info").Where("id = ?", id).First(&res).Error
	return
}
func (m Mysql) VideoInfoQueryByAuthId(authId string, page, size int) (res []*models.VideoInfo, total int64, err error) {
	err = m.Db.Table("video_info").Where("author_id = ?", authId).Offset((page - 1) * size).Limit(size).
		Find(&res).Count(&total).Error
	return
}
func (m Mysql) VideoInfoSaveById(video *models.VideoInfo) (err error) {
	err = m.Db.Table("video_info").Where("id = ?", video.ID).Save(&video).Error
	return
}
func (m Mysql) VideoInfoDelByUid(uid string) (src string, err error) {
	var res *models.VideoInfo
	err = m.Db.Table("video_info").Unscoped().Where("video_id = ?", uid).First(&res).Delete(&models.VideoInfo{}).Error
	src = res.Src
	return
}
func (m Mysql) VideoInfoQueryLikeName(name string, page, size int) (res []*models.VideoInfo, total int64, err error) {
	err = m.Db.Table("video_info").Where("name like ?", LikeType+name+LikeType).
		Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
func (m Mysql) VideoInfoQueryRandom(val string, size int, oldList []int) (res []*models.VideoInfo, err error) {
	var count int64
	//是否有视频
	m.Db.Table("video_info").Count(&count)
	if count == 0 {
		return
	}
	//是否上传了OldList
	if len(oldList) == 0 {
		oldList = append(oldList, 0)
	}
	//randomInt := models.GetRandomInt(size, int(count), oldList)
	//fmt.Println("-----------", randomInt, "--------------")
	//if len(randomInt) == 0 {
	//	return
	//}
	for i := 0; i < size; i++ {
		var demo *models.VideoInfo
		err = m.Db.Table("video_info").Where("id not in (?)", oldList).Take(&demo).Error
		if err != nil {
			return
		}
		res = append(res, demo)
		oldList = append(oldList, int(demo.ID))
	}
	return
}
func (m Mysql) VideoInfoQueryByAuthor(ID string, page, size int) (res []*models.VideoInfo, total int64, err error) {
	err = m.Db.Table("video_info").Where("author_id  =  ?", ID).
		Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
